package org.example.demo1.controller;

import com.rometools.rome.feed.atom.Feed;
import org.example.demo1.service.AiAgentService;
import org.example.demo1.service.FeedbackCollectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


//主要是完成向大模型发送对话
@CrossOrigin
@RestController
@RequestMapping("/ai/agent")
public class AiAgentController {

    private final AiAgentService aiAgentService;

    @Autowired
    private FeedbackCollectionService feedbackService;

    @Autowired
    public AiAgentController(AiAgentService aiAgentService) {
        this.aiAgentService = aiAgentService;
    }

    @GetMapping("/process")
    public String processCommand(@RequestParam String command, @RequestParam(required = false) String sessionId) {
        // 如果没有提供sessionId，生成一个新的
        if (sessionId == null || sessionId.trim().isEmpty()) {
            sessionId = generateSessionId();
        }
        // 获取AI回答
        String aiResponse = aiAgentService.processCommand(command, sessionId);

        // 记录AI回答，准备收集反馈
        String feedbackId = feedbackService.recordAIResponse(
                sessionId, command, aiResponse, extractToolsUsed(aiResponse));

        // 在AI回答后添加反馈请求
        String responseWithFeedback = aiResponse + "\n\n" + generateFeedbackPrompt(feedbackId);

        return responseWithFeedback;  }

    private String generateFeedbackPrompt(String feedbackId) {
        return String.format("""
        ---
        💡 **这个解决方案对您有帮助吗？**
        
        您的反馈将帮助我们改进知识库！
        
        **反馈ID**: `%s`
        
        请点击下方按钮提供反馈：
        """, feedbackId);
    }

    // 处理反馈
    @PostMapping("/feedback")
    public ResponseEntity<Map<String, Object>> submitFeedback(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            String feedbackId = (String) request.get("feedbackId");
            Boolean isEffective = (Boolean) request.get("effective");
            String comment = (String) request.getOrDefault("comment", "");

            String result = feedbackService.processFeedback(feedbackId, isEffective, comment);

            response.put("success", true);
            response.put("message", result);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "处理反馈失败: " + e.getMessage());
        }
        return ResponseEntity.ok(response);
    }


    // 获取所有会话列表
    @GetMapping("/sessions")
    public ResponseEntity<Map<String, Object>> getSessions() {
        Map<String, Object> response = new HashMap<>();
        try {
            List<Map<String, Object>> sessions = aiAgentService.getAllSessions();
            response.put("success", true);
            response.put("sessions", sessions);
            response.put("message", "Sessions retrieved successfully");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "Failed to retrieve sessions: " + e.getMessage());
            response.put("sessions", new ArrayList<>());
        }
        return ResponseEntity.ok(response);
    }

    // 获取指定会话的消息
    @GetMapping("/sessions/{sessionId}/messages")
    public ResponseEntity<Map<String, Object>> getSessionMessages(@PathVariable String sessionId) {
        Map<String, Object> response = new HashMap<>();
        try {
            List<Map<String, Object>> messages = aiAgentService.getSessionMessages(sessionId);
            response.put("success", true);
            response.put("messages", messages);
            response.put("sessionId", sessionId);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "Failed to retrieve messages: " + e.getMessage());
            response.put("messages", new ArrayList<>());
        }
        return ResponseEntity.ok(response);
    }

    // 创建新会话
    @PostMapping("/sessions")
    public ResponseEntity<Map<String, Object>> createSession(@RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            String title = request.getOrDefault("title", "新对话");
            String sessionId = aiAgentService.createNewSession(title);
            response.put("success", true);
            response.put("sessionId", sessionId);
            response.put("message", "Session created successfully");
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "Failed to create session: " + e.getMessage());
        }
        return ResponseEntity.ok(response);
    }

    // 删除会话
    @DeleteMapping("/sessions/{sessionId}")
    public ResponseEntity<Map<String, Object>> deleteSession(@PathVariable String sessionId) {
        Map<String, Object> response = new HashMap<>();
        try {
            boolean deleted = aiAgentService.deleteSession(sessionId);
            if (deleted) {
                response.put("success", true);
                response.put("message", "Session deleted successfully");
            } else {
                response.put("success", false);
                response.put("message", "Session not found or could not be deleted");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "Failed to delete session: " + e.getMessage());
        }
        return ResponseEntity.ok(response);
    }

    // 更新会话标题
    @PutMapping("/sessions/{sessionId}")
    public ResponseEntity<Map<String, Object>> updateSession(@PathVariable String sessionId,
                                                             @RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();
        try {
            String title = request.get("title");
            boolean updated = aiAgentService.updateSessionTitle(sessionId, title);
            if (updated) {
                response.put("success", true);
                response.put("message", "Session updated successfully");
            } else {
                response.put("success", false);
                response.put("message", "Session not found");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "Failed to update session: " + e.getMessage());
        }
        return ResponseEntity.ok(response);
    }

    private String generateSessionId() {
        return "session_" + System.currentTimeMillis() + "_" +
                java.util.UUID.randomUUID().toString().substring(0, 8);
    }

    /**
     * 从AI回答中提取使用的工具列表
     */
    private List<String> extractToolsUsed(String aiResponse) {
        List<String> tools = new ArrayList<>();

        if (aiResponse == null || aiResponse.trim().isEmpty()) {
            return tools;
        }

        String lowerResponse = aiResponse.toLowerCase();

        // 检测各种工具调用的关键词
        if (lowerResponse.contains("checkclusterhealth") || lowerResponse.contains("集群健康检查")) {
            tools.add("集群健康检查");
        }
        if (lowerResponse.contains("getpodstatusoverview") || lowerResponse.contains("pod状态概览")) {
            tools.add("Pod状态概览");
        }
        if (lowerResponse.contains("getpoddetailedinfo") || lowerResponse.contains("pod详细信息")) {
            tools.add("Pod详细信息");
        }
        if (lowerResponse.contains("getpodlogs") || lowerResponse.contains("pod日志")) {
            tools.add("Pod日志获取");
        }
        if (lowerResponse.contains("identifyproblemPods") || lowerResponse.contains("识别问题pod")) {
            tools.add("问题Pod识别");
        }
        if (lowerResponse.contains("restartpod") || lowerResponse.contains("重启pod")) {
            tools.add("Pod重启");
        }
        if (lowerResponse.contains("getpodresourceusage") || lowerResponse.contains("资源使用情况")) {
            tools.add("资源使用监控");
        }
        if (lowerResponse.contains("getallnamespaces") || lowerResponse.contains("所有命名空间")) {
            tools.add("命名空间查询");
        }
        if (lowerResponse.contains("getallpodsoverview") || lowerResponse.contains("所有pod概览")) {
            tools.add("集群Pod概览");
        }

        // CPU相关工具检测
        if (lowerResponse.contains("detectcpustress") || lowerResponse.contains("cpu压力检测")) {
            tools.add("CPU压力检测");
        }
        if (lowerResponse.contains("analyzepodcpupattern") || lowerResponse.contains("cpu模式分析")) {
            tools.add("CPU模式分析");
        }
        if (lowerResponse.contains("checkstresschaos") || lowerResponse.contains("stresschaos检查")) {
            tools.add("StressChaos检查");
        }
        if (lowerResponse.contains("pausestresschaos") || lowerResponse.contains("暂停压力测试")) {
            tools.add("暂停StressChaos");
        }
        if (lowerResponse.contains("resumestresschaos") || lowerResponse.contains("恢复压力测试")) {
            tools.add("恢复StressChaos");
        }

        // 如果没有检测到具体工具，但包含工具调用的特征，添加通用标识
        if (tools.isEmpty() && (lowerResponse.contains("工具调用") || lowerResponse.contains("🔧"))) {
            tools.add("Kubernetes诊断工具");
        }

        return tools;
    }

    public static class CommandRequest {
        private String request;

        public String getRequest() {
            return request;
        }

        public void setRequest(String request) {
            this.request = request;
        }
    }
}
